﻿using System;
using System.Collections;
using System.Data;
using System.Text;
using FS.Business;
using FS.Common.DotNetBean;
using FS.Common.DotNetCode;
using FS.Common.DotNetData;
using FS.Common.DotNetEncrypt;
using FS.Common.DotNetUI;

namespace FS.Web.BLL.SysUser
{
    public partial class UserInfo_Form : PageBase
    {
        public StringBuilder strRoleHtml = new StringBuilder();
        public StringBuilder strUserRightHtml = new StringBuilder();

        private string _key;
        protected void Page_Load(object sender, EventArgs e)
        {
            this._key = base.Request["key"];
            this.CreateUserName.Value = RequestSession.GetSessionUser().UserName.ToString();
            this.CreateDate.Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            
            this.InitInfoRole();
            this.InitUserRight();
            if (!base.IsPostBack)
            {
                if (!string.IsNullOrEmpty(this._key))
                {
                    this.InitData();
                }
            }
        }
        private void InitData()
        {
            Hashtable ht = DataFactory.Run().GetHashtableById("Sys_UserInfo", "User_ID", this._key);
            if (ht.Count > 0 && ht != null)
            {
                ControlBindHelper.SetWebControls(this.Page, ht);
                this.User_Pwd.Value = "*************";
            }
        }

        public void InitInfoRole()
        {
            DataTable dtRole = this._sys_idao.InitRoleList();
            DataTable dtUserRole = this._sys_idao.InitUserRoleByUser(this._key);
            if (DataTableHelper.IsExistRows(dtRole))
            {
                foreach (DataRowView drv in new DataView(dtRole)
                {
                    RowFilter = "ParentId = '0'"
                })
                {
                    this.strRoleHtml.Append("<li>");
                    this.strRoleHtml.Append(string.Concat(new object[]
					{
						"<div><input style='vertical-align: middle;margin-bottom:2px;' type=\"checkbox\" ",
						this.GetChecked("Roles_ID", drv["Roles_ID"].ToString(), dtUserRole),
						" value=\"",
						drv["Roles_ID"],
						"|所属角色\" name=\"checkbox\" />"
					}));
                    this.strRoleHtml.Append(drv["Roles_Name"].ToString() + "</div>");
                    this.strRoleHtml.Append(this.GetTreeNodeRole(drv["Roles_ID"].ToString(), dtRole, dtUserRole));
                    this.strRoleHtml.Append("</li>");
                }
            }
            else
            {
                this.strRoleHtml.Append("<li>");
                this.strRoleHtml.Append("<div><span style='color:red;'>暂无数据</span></div>");
                this.strRoleHtml.Append("</li>");
            }
        }
        public string GetTreeNodeRole(string parentID, DataTable dtNode, DataTable dtUserRole)
        {
            StringBuilder sb_TreeNode = new StringBuilder();
            DataView dv = new DataView(dtNode);
            dv.RowFilter = "ParentId = '" + parentID + "'";
            if (dv.Count > 0)
            {
                sb_TreeNode.Append("<ul>");
                foreach (DataRowView drv in dv)
                {
                    sb_TreeNode.Append("<li>");
                    sb_TreeNode.Append("<div class='treeview-file'>");
                    sb_TreeNode.Append(string.Concat(new object[]
					{
						"<input style='vertical-align: middle;margin-bottom:2px;' type=\"checkbox\" ",
						this.GetChecked("Roles_ID", drv["Roles_ID"].ToString(), dtUserRole),
						" value=\"",
						drv["Roles_ID"],
						"|所属角色\" name=\"checkbox\" />"
					}));
                    sb_TreeNode.Append(drv["Roles_Name"].ToString() + "</div>");
                    sb_TreeNode.Append(this.GetTreeNodeRole(drv["Roles_ID"].ToString(), dtNode, dtUserRole));
                    sb_TreeNode.Append("</li>");
                }
                sb_TreeNode.Append("</ul>");
            }
            return sb_TreeNode.ToString();
        }


        public void InitUserRight()
        {
            DataTable dtList = this._sys_idao.GetMenuBind();
            DataTable dtUserRight = this._sys_idao.InitUserRight(this._key);
            if (DataTableHelper.IsExistRows(dtList))
            {
                DataTable dtButoon = DataTableHelper.GetNewDataTable(dtList, "Menu_Type = '3'");
                DataTable dtMenu = DataTableHelper.GetNewDataTable(dtList, "Menu_Type < '3'");
                DataView dv = new DataView(dtMenu);
                dv.RowFilter = " ParentId = '0'";
                int eRowIndex = 0;
                foreach (DataRowView drv in dv)
                {
                    string trID = "node-" + eRowIndex.ToString();
                    this.strUserRightHtml.Append("<tr id='" + trID + "'>");
                    this.strUserRightHtml.Append("<td style='width: 200px;padding-left:20px;'><span class=\"folder\">" + drv["Menu_Name"] + "</span></td>");
                    if (!string.IsNullOrEmpty(drv["Menu_Img"].ToString()))
                    {
                        this.strUserRightHtml.Append("<td style='width: 30px;text-align:center;'><img src='/Themes/images/32/" + drv["Menu_Img"] + "' style='width:16px; height:16px;vertical-align: middle;' alt=''/></td>");
                    }
                    else
                    {
                        this.strUserRightHtml.Append("<td style='width: 30px;text-align:center;'><img src='/Themes/images/32/5005_flag.png' style='width:16px; height:16px;vertical-align: middle;' alt=''/></td>");
                    }
                    this.strUserRightHtml.Append(string.Concat(new object[]
					{
						"<td style=\"width: 23px; text-align: left;\"><input id='ckb",
						trID,
						"' onclick=\"ckbValueObj(this.id)\" style='vertical-align: middle;margin-bottom:2px;' type=\"checkbox\" ",
						this.GetChecked("Menu_Id", drv["Menu_Id"].ToString(), dtUserRight),
						"  value=\"",
						drv["Menu_Id"],
						"|用户权限\" name=\"checkbox\" /></td>"
					}));
                    this.strUserRightHtml.Append("<td>" + this.GetButton(drv["Menu_Id"].ToString(), dtButoon, trID, dtUserRight) + "</td>");
                    this.strUserRightHtml.Append("</tr>");
                    this.strUserRightHtml.Append(this.GetTreeNodeUserRight(drv["Menu_Id"].ToString(), dtMenu, trID, dtButoon, dtUserRight));
                    eRowIndex++;
                }
            }
        }
        public string GetTreeNodeUserRight(string parentID, DataTable dtMenu, string parentTRID, DataTable dtButoon, DataTable dtUserRight)
        {
            StringBuilder sb_TreeNode = new StringBuilder();
            DataView dv = new DataView(dtMenu);
            dv.RowFilter = "ParentId = '" + parentID + "'";
            int i = 1;
            foreach (DataRowView drv in dv)
            {
                string trID = parentTRID + "-" + i.ToString();
                sb_TreeNode.Append(string.Concat(new string[]
				{
					"<tr id='",
					trID,
					"' class='child-of-",
					parentTRID,
					"'>"
				}));
                sb_TreeNode.Append("<td style='padding-left:20px;'><span class=\"folder\">" + drv["Menu_Name"].ToString() + "</span></td>");
                if (!string.IsNullOrEmpty(drv["Menu_Img"].ToString()))
                {
                    sb_TreeNode.Append("<td style='width: 30px;text-align:center;'><img src='/Themes/images/32/" + drv["Menu_Img"].ToString() + "' style='width:16px; height:16px;vertical-align: middle;' alt=''/></td>");
                }
                else
                {
                    sb_TreeNode.Append("<td style='width: 30px;text-align:center;'><img src='/Themes/images/32/5005_flag.png' style='width:16px; height:16px;vertical-align: middle;' alt=''/></td>");
                }
                sb_TreeNode.Append(string.Concat(new object[]
				{
					"<td style=\"width: 23px; text-align: left;\"><input id='ckb",
					trID,
					"' onclick=\"ckbValueObj(this.id)\" ",
					this.GetChecked("Menu_Id", drv["Menu_Id"].ToString(), dtUserRight),
					" style='vertical-align: middle;margin-bottom:2px;' type=\"checkbox\" value=\"",
					drv["Menu_Id"],
					"|用户权限\" name=\"checkbox\" /></td>"
				}));
                sb_TreeNode.Append("<td>" + this.GetButton(drv["Menu_Id"].ToString(), dtButoon, trID, dtUserRight) + "</td>");
                sb_TreeNode.Append("</tr>");
                sb_TreeNode.Append(this.GetTreeNodeUserRight(drv["Menu_Id"].ToString(), dtMenu, trID, dtButoon, dtUserRight));
                i++;
            }
            return sb_TreeNode.ToString();
        }
        public string GetButton(string Menu_Id, DataTable dt, string parentTRID, DataTable dtUserRight)
        {
            StringBuilder ButtonHtml = new StringBuilder();
            DataTable dt_Button = DataTableHelper.GetNewDataTable(dt, "ParentId = '" + Menu_Id + "'");
            string result;
            if (DataTableHelper.IsExistRows(dt_Button))
            {
                int i = 1;
                foreach (DataRow drv in dt_Button.Rows)
                {
                    string trID = parentTRID + "--" + i.ToString();
                    ButtonHtml.Append(string.Concat(new object[]
					{
						"<lable><input id='ckb",
						trID,
						"' onclick=\"ckbValueObj(this.id)\" ",
						this.GetChecked("Menu_Id", drv["Menu_Id"].ToString(), dtUserRight),
						" style='vertical-align: middle;margin-bottom:2px;' type=\"checkbox\" value=\"",
						drv["Menu_Id"],
						"|用户权限\" name=\"checkbox\" />"
					}));
                    ButtonHtml.Append(drv["Menu_Name"].ToString() + "</lable>&nbsp;&nbsp;&nbsp;&nbsp;");
                    i++;
                }
                result = ButtonHtml.ToString();
            }
            else
            {
                result = ButtonHtml.ToString();
            }
            return result;
        }
        public string GetChecked(string pkName, string Obj_Val, DataTable dt)
        {
            StringBuilder strSql = new StringBuilder();
            dt = DataTableHelper.GetNewDataTable(dt, pkName + " = '" + Obj_Val + "'");
            string result;
            if (DataTableHelper.IsExistRows(dt))
            {
                result = "checked=\"checked\"";
            }
            else
            {
                result = "";
            }
            return result;
        }
        protected void Save_Click(object sender, EventArgs e)
        {
            string guid = CommonHelper.GetGuid;
            Hashtable ht = new Hashtable();
            ht["User_Name"] = this.User_Name.Value;
            ht["User_Account"] = this.User_Account.Value;
            ht["User_Pwd"] = Md5Helper.MD5(this.User_Pwd.Value, 32);           
            ht["Email"] = this.Email.Value;
            ht["User_Remark"] = this.User_Remark.Value;
            ht["isViewSupply"] = this.isViewSupply.Value;
            ht["isViewPrice"] = this.isViewPrice.Value;
            ht["isViewCost"] = this.isViewCost.Value;
            ht["isViewAll"] = this.isViewAll.Value;

            if (!string.IsNullOrEmpty(this._key))
            {
                guid = this._key;
                ht["ModifyDate"] = DateTime.Now;
                if (string.IsNullOrEmpty(this.password.Value))
                {
                    ht.Remove("User_Pwd");
                }
                ht["ModifyUserId"] = RequestSession.GetSessionUser().UserId;
                ht["ModifyUserName"] = RequestSession.GetSessionUser().UserName;
            }
            else
            {
                ht["User_ID"] = guid;
                ht["CreateUserId"] = RequestSession.GetSessionUser().UserId;
                ht["CreateUserName"] = RequestSession.GetSessionUser().UserName;
            }
            bool IsOk = DataFactory.Run().Submit_AddOrEdit("Sys_UserInfo", "User_ID", this._key, ht);
            if (IsOk)
            {
                IsOk = this.add_ItemForm(this.checkbox_value.Value.Split(new char[]
					{
						','
					}), guid);
            }
            if (IsOk)
            {
                //重新计算用户权限
                CacheHelper.RemoveAllCache("KeyPermission_URL");
                CacheHelper.RemoveAllCache("AllUser"); 
                ShowMsgHelper.AlertMsg("操作成功！");
            }
            else
            {
                ShowMsgHelper.Alert_Error("操作失败！");
            }
        }
        public bool add_ItemForm(string[] item_value, string user_id)
        {
            bool result;
            try
            {
                StringBuilder[] sqls = new StringBuilder[item_value.Length + 2];
                object[] objs = new object[item_value.Length + 2];

                StringBuilder sbDelete_Role = new StringBuilder();
                sbDelete_Role.Append("Delete From Sys_UserRole Where User_ID =@User_ID");
                SqlParam[] parm_Role = new SqlParam[]
				{
					new SqlParam("@User_ID", user_id)
				};
                sqls[0] = sbDelete_Role;
                objs[0] = parm_Role;

                StringBuilder sbDelete_Right = new StringBuilder();
                sbDelete_Right.Append("Delete From Sys_UserRight Where User_ID =@User_ID");
                SqlParam[] parm_Right = new SqlParam[]
				{
					new SqlParam("@User_ID", user_id)
				};
                sqls[1] = sbDelete_Right;
                objs[1] = parm_Right;

                int index = 2;
                for (int i = 0; i < item_value.Length; i++)
                {
                    string item = item_value[i];
                    if (item.Length > 0)
                    {
                        string[] str_item = item.Split(new char[]
						{
							'|'
						});
                        string key = str_item[0];
                        string type = str_item[1];

                        if (type == "所属角色")
                        {
                            StringBuilder sbadd = new StringBuilder();
                            sbadd.Append("Insert into Sys_UserRole(");
                            sbadd.Append("UserRole_ID,User_ID,Roles_ID,CreateUserId,CreateUserName");
                            sbadd.Append(")Values(");
                            sbadd.Append("@UserRole_ID,@User_ID,@Roles_ID,@CreateUserId,@CreateUserName)");
                            SqlParam[] parmAdd = new SqlParam[]
							{
								new SqlParam("@UserRole_ID", CommonHelper.GetGuid),
								new SqlParam("@User_ID", user_id),
								new SqlParam("@Roles_ID", key),
								new SqlParam("@CreateUserId", RequestSession.GetSessionUser().UserId),
								new SqlParam("@CreateUserName", RequestSession.GetSessionUser().UserName)
							};
                            sqls[index] = sbadd;
                            objs[index] = parmAdd;
                        }
                        else
                        {
                            if (type == "用户权限")
                            {
                                StringBuilder sbadd = new StringBuilder();
                                sbadd.Append("Insert into Sys_UserRight(");
                                sbadd.Append("UserRight_ID,User_ID,Menu_Id,CreateUserId,CreateUserName");
                                sbadd.Append(")Values(");
                                sbadd.Append("@UserRight_ID,@User_ID,@Menu_Id,@CreateUserId,@CreateUserName)");
                                SqlParam[] parmAdd = new SqlParam[]
								{
									new SqlParam("@UserRight_ID", CommonHelper.GetGuid),
									new SqlParam("@User_ID", user_id),
									new SqlParam("@Menu_Id", key),
									new SqlParam("@CreateUserId", RequestSession.GetSessionUser().UserId),
									new SqlParam("@CreateUserName", RequestSession.GetSessionUser().UserName)
								};
                                sqls[index] = sbadd;
                                objs[index] = parmAdd;
                            }
                        }
                        index++;
                    }
                }
                result = (DataFactory.Run().BatchExecuteBySql(sqls, objs) >= 0);
            }
            catch
            {
                result = false;
            }
            return result;
        }
    }
}
